﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Lswweb.Common;

namespace Lswweb.Domain.ResourceConfiguration
{
    public class ResourceUrls : ResourceBase<string,Url>
    {
        public ResourceUrls(string filePath) : base(filePath) { }

        protected override KeyValuePair<string, Url> GetPairByXmlNode(XmlNode node)
        {
            string name = node.Attributes["name"].Value;
            string path = UrlHandler(node.Attributes["path"].Value);
            ReWrittenUrl urlRewrite = GetRewriterByXmlNode(name,node);

            return new KeyValuePair<string, Url>(
                name,
                new Url(name, path, urlRewrite));
        }

        private ReWrittenUrl GetRewriterByXmlNode(string name,XmlNode node)
        {
            XmlAttribute vanity = node.Attributes["vanity"];
            XmlAttribute pattern = node.Attributes["pattern"];
            if (vanity != null && pattern != null)
            {
                 return new ReWrittenUrl(
                    name,
                    UrlHandler(pattern.Value),
                    UrlHandler(vanity.Value));
            }

            return null;
        }

        /// <summary>
        /// 对url字符进处理，如一些在xml中需要转换的特殊符号等
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string UrlHandler(string urlStr)
        {
            if (string.IsNullOrEmpty(urlStr))
                return string.Empty;

            //xml文件不支持&符号，所以使用^符号替代
            string url=urlStr.Replace("^","&");

            //根据虚拟主机应用程序路径组合成完整url
            return UrlHelper.ResolveUrl(url);
        }
    }
}
